package com.yunshan.welfare;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunshan.common.utils.StringUtils;
import com.yunshan.member.domain.MemberUserInfo;
import com.yunshan.mp.domain.ResultServe;
import com.yunshan.welfare.domain.WelfareGift;
import com.yunshan.welfare.service.IWelfareGiftService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.yunshan.common.annotation.Log;
import com.yunshan.common.core.controller.BaseController;
import com.yunshan.common.core.domain.AjaxResult;
import com.yunshan.common.enums.BusinessType;
import com.yunshan.welfare.domain.WelfareGiftRecord;
import com.yunshan.welfare.service.IWelfareGiftRecordService;
import com.yunshan.common.utils.poi.ExcelUtil;
import com.yunshan.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import static com.yunshan.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 礼包发放详情Controller
 *
 * @author yunshan
 * @date 2025-01-20
 */
@Api(tags = "礼包发放详情管理")
@RestController
@RequestMapping("/welfare/giftRecord")
public class WelfareGiftRecordController extends BaseController
{
    @Autowired
    private IWelfareGiftRecordService welfareGiftRecordService;

    // 手机号正则表达式
    private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";

    /**
     * 查询礼包发放详情列表
     */
    @ApiOperation(value = "查询礼包发放详情列表")
    @GetMapping("/list")
    public TableDataInfo list(WelfareGiftRecord welfareGiftRecord)
    {
        startPage();
        List<WelfareGiftRecord> list = welfareGiftRecordService.selectWelfareGiftRecordListGroup(welfareGiftRecord);
        return getDataTable(list);
    }

    /**
     * 查询礼包发放详情列表（不分页）
     */
    @ApiOperation(value = "查询礼包发放详情列表（不分页）")
    @GetMapping("/query")
    public AjaxResult query(WelfareGiftRecord welfareGiftRecord)
    {
        List<ResultServe> welfareGiftRecords = welfareGiftRecordService.selecResultGiftRecordList(welfareGiftRecord);
        return success(welfareGiftRecords);
    }

    /**
     * 导出礼包发放详情列表
     */
    @Log(title = "礼包发放详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WelfareGiftRecord welfareGiftRecord)
    {
        List<WelfareGiftRecord> list = welfareGiftRecordService.selectWelfareGiftRecordList(welfareGiftRecord);
        ExcelUtil<WelfareGiftRecord> util = new ExcelUtil<WelfareGiftRecord>(WelfareGiftRecord.class);
        util.exportExcel(response, list, "礼包发放详情数据");
    }

    /**
     * 获取礼包发放详情详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(welfareGiftRecordService.selectWelfareGiftRecordById(id));
    }

    /**
     * 新增礼包发放
     */
    @ApiOperation("发放礼包")
    @Log(title = "礼包发放", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Map<String, Object> map)
    {
        try {
            WelfareGiftRecord welfareGiftRecord = new ObjectMapper()
                    .convertValue(map.get("welfareGiftRecord"), WelfareGiftRecord.class);

            Object rawIds = map.get("ids");
            if (!(rawIds instanceof List<?>)) {
                return error("ids参数格式错误");
            }

            List<Long> ids = ((List<?>) rawIds).stream()
                    .map(obj -> {
                        if (obj instanceof Number) {
                            return ((Number) obj).longValue();
                        }
                        throw new IllegalArgumentException("ids列表包含非数值类型数据");
                    })
                    .collect(Collectors.toList());

            if (StringUtils.isEmpty(welfareGiftRecord.getEndTimes())){
                return error("请填写礼包有效期");
            }
            return success(welfareGiftRecordService.insertWelfareGiftRecord(welfareGiftRecord, ids));
        }catch (Exception e){
            log.error("发放失败：{}",e.getMessage());
            return error(e.getMessage());
        }
    }

    /**
     * 修改礼包发放详情
     */
    @Log(title = "礼包发放详情", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WelfareGiftRecord welfareGiftRecord)
    {
        return toAjax(welfareGiftRecordService.updateWelfareGiftRecord(welfareGiftRecord));
    }

    /**
     * 删除礼包发放详情
     */
    @Log(title = "礼包发放详情", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(welfareGiftRecordService.deleteWelfareGiftRecordByIds(ids));
    }

    @PostMapping("/download-template")
    public ResponseEntity<byte[]> downloadExcelTemplate() throws IOException {
        // 创建一个新的工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建一个工作表
        Sheet sheet = workbook.createSheet("Template");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerCellStyle.setFont(headerFont);

        Cell headerCell = headerRow.createCell(0);
        headerCell.setCellValue("姓名");
        headerCell.setCellStyle(headerCellStyle);

        headerCell = headerRow.createCell(1);
        headerCell.setCellValue("手机号");
        headerCell.setCellStyle(headerCellStyle);

        // 自动调整列宽
        sheet.autoSizeColumn(0);
        sheet.autoSizeColumn(1);

        // 将工作簿写入字节数组输出流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        workbook.close();

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "template.xlsx");

        return new ResponseEntity<>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK);
    }

    @ApiOperation("批量发放礼包")
    @Log(title = "礼包发放", businessType = BusinessType.INSERT)
    @PostMapping("/batch-import")
    public AjaxResult batchImport(
            @RequestParam("giftId") Long giftId,
            @RequestParam("file") MultipartFile file,
            @RequestParam("endTimes") String endTimes) {
        try {

            // 1. 校验文件有效性
            if (file.isEmpty()) {
                return error("请选择要上传的文件");
            }
            if (!file.getOriginalFilename().endsWith(".xlsx")) {
                return error("仅支持xlsx格式文件");
            }

            // 2. 解析Excel数据
            List<MemberUserInfo> userList = new ArrayList<>();
            try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
                Sheet sheet = workbook.getSheetAt(0);

                for (int i = 1; i <= sheet.getLastRowNum(); i++) { // 从第2行开始
                    Row row = sheet.getRow(i);
                    if (row == null) {
                        continue;
                    }

                    MemberUserInfo user = new MemberUserInfo();
                    // 解析姓名（A列）
                    user.setName(getCellStringValue(row.getCell(0)));
                    // 解析手机号（B列）
                    user.setPhone(getCellStringValue(row.getCell(1)));

                    // 数据校验
                    if (StringUtils.isEmpty(user.getName())) {
                        return error("第" + (i + 1) + "行姓名不能为空");
                    }
                    if (!user.getPhone().matches(PHONE_REGEX)) {
                        return error("第" + (i + 1) + "行手机号格式错误");
                    }

                    userList.add(user);
                }
            }

            // 3. 调用服务层进行批量保存
            return success(welfareGiftRecordService.batchInsertGiftRecords(giftId, userList, endTimes));
        }catch (Exception e){
            log.error("发放失败：{}",e.getMessage());
            return error(e.getMessage());
        }

    }

    // 辅助方法：获取单元格值
    private String getCellStringValue(Cell cell) {
        if (cell == null){ return "";}
        cell.setCellType(CellType.STRING);
        return cell.getStringCellValue().trim();
    }


}
